//
//  SLHTTPClient.m
//  LSNets
//
//  Created by Samuel on 12/9/14.
//
//

#import "SHTTPClient.h"
#import "AFURLSessionManager.h"
#import "SUrlBase.h"
#import "SUrlDeploy.h"

#import "SDebugWindow.h"
#import "SFlieManage.h"
@implementation SHTTPClient
#pragma mark ********************自定义封装方法********************
static SHTTPClient *sClient = nil;
+ (SHTTPClient *)sharedClient;
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sClient = [[SHTTPClient alloc]init];
    });
    return sClient;
}
- (void)setIsOpneRecordRequest:(BOOL)isOpneRecordRequest
{
    _isOpneRecordRequest = isOpneRecordRequest;
    if(!self.sDwindow)
    {
        SDebugWindow *sDw = [SDebugWindow shareSDebugWindowInitialization];
        self.sDwindow = sDw;
    }
}
+ (void)GetBaseForConnection:(NSString *)path
                 _Parameters:(NSMutableDictionary *)parameters
                       block:(void(^)(id rDictionary))processResult
                   failblock:(void(^)(NSError *error))failResult
{
    SHTTPSessionClient *session = [SHTTPSessionClient sharedSessionClientWithUrl:[SUrlDeploy getSettingUrls]];
    [session GET_Path_Session:path
                  _Parameters:parameters
                        block:^(id rDictionary, NSURLSessionDataTask *rTask) {
                            SNLog(@"path => %@\n\nparameters => %@\nresponse => %@\n",path,parameters,[[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:rDictionary options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]);
                            if ([SHTTPClient sharedClient].isOpneRecordRequest) {
                                SDebugWindow *sdv = (SDebugWindow*)[SHTTPClient sharedClient].sDwindow;
                                [sdv showDatasWithObject:rDictionary andUrl:[NSString stringWithFormat:@"%@%@",[SUrlDeploy getSettingUrls],path]];
                            }
                            (rDictionary==nil)?failResult(nil):processResult(rDictionary);
                        } failblock:^(NSError *error, NSURLSessionDataTask *rTask) {
                            SNLog(@"path => %@\n\nerror => %@\n",path,error);
//                            [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
                            failResult(error);
                        }];
}
+ (void)PostBaseForConnection:(NSString *)path
                  _Parameters:(NSMutableDictionary *)parameters
                        block:(void(^)(id rDictionary))processResult
                    failblock:(void(^)(NSError *error))failResult
{
    SHTTPSessionClient *session = [SHTTPSessionClient sharedSessionClientWithUrl:[SUrlDeploy getSettingUrls]];
    [session POST_Path_Session:path
                   _Parameters:parameters
                         block:^(id rDictionary, NSURLSessionDataTask *rTask) {
                             SNLog(@"path => %@\n\nparameters => %@\nresponse => %@\n",path,parameters,[[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:rDictionary options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]);
                             if ([SHTTPClient sharedClient].isOpneRecordRequest) {
                                 SDebugWindow *sdv = (SDebugWindow*)[SHTTPClient sharedClient].sDwindow;
                                 [sdv showDatasWithObject:rDictionary andUrl:[NSString stringWithFormat:@"%@%@",[SUrlDeploy getSettingUrls],path]];
                             }
                             (rDictionary==nil)?failResult(nil):processResult(rDictionary);
                         } failblock:^(NSError *error, NSURLSessionDataTask *rTask) {
                             SNLog(@"path => %@\n\nerror => %@\n",path,error);
                             failResult(error);
                         }];
}
+ (void)coustomRequestOfData:(NSData*)data
                    DataName:(NSString*)dataName
                         Url:(NSString*)url
                        Path:(NSString*)path
                  Parameters:(NSMutableDictionary*)parameters
                        Type:(NSString*)type
                       block:(void(^)(id rDictionary))processResult
                   failblock:(void(^)(NSError *error))failResult;
{
    NSString *urls = [NSString stringWithFormat:@"%@%@",url,path];
    if ([type isEqualToString:@"GET"]) {
        urls = [NSString stringWithFormat:@"https://api.weixin.qq.com/cgi-bin/media/get?access_token=%@&media_id=%@",[parameters objectForKey:@"access_token"],[parameters objectForKey:@"media_id"]];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urls]];
        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request
                                                                         progress:nil
                                                                      destination:^NSURL *(NSURL *targetPath,NSURLResponse *response)
                                                  {
                                                      /**
                                                       图片文件名 时间戳
                                                       */
                                                      NSTimeInterval at =[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]*1000;
                                                      NSString *vNamesString = [NSString stringWithFormat:@"%.f",at];
                                                      /**
                                                       本月文件夹名 时间日期
                                                       */
                                                      NSDateFormatter *vDocumentName = [[NSDateFormatter  alloc]init];
                                                      [vDocumentName setDateFormat:@"yyyyMM"];
                                                      NSString *vDocumentNameString = [NSString stringWithFormat:@"EZR%@",[vDocumentName stringFromDate:[NSDate date]]];
                                                      /**
                                                       *  沙盒存儲
                                                       */
                                                      
                                                      NSString *fileDirectory = [[SFlieManage shareSFlieManage]getDocumentsPathWithCreateAndPath:[DOCUMENTS_VOICE_NAME stringByAppendingPathComponent:vDocumentNameString]];
                                                      return [NSURL fileURLWithPath:[fileDirectory stringByAppendingPathComponent:[vNamesString stringByAppendingPathExtension:@"amr"]]];
                                                  } completionHandler:^(NSURLResponse *response,NSURL *filePath, NSError *error)
                                                  {
                                                      if (error) {
                                                          failResult(error);
                                                      }
                                                      else
                                                      {
                                                          NSString *path = [NSString stringWithFormat:@"%@",filePath];
                                                          processResult([NSDictionary dictionaryWithObjectsAndKeys:[path lastPathComponent],@"fileName", nil]);
                                                          
                                                      }
                                                  }];
        [downloadTask resume];
        return;
    }
    AFHTTPSessionManager *requestObject = [SHTTPClient sharedSessionByCoustom:urls];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urls parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                    {
                                        [formData appendPartWithFileData:data name:dataName fileName:dataName mimeType:@"text/plain"];
                                    } error:nil];
    
    
    NSURLSessionUploadTask *uploadTask = [requestObject uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error)
                                          {
                                              if (error) {
                                                  failResult(error);
                                              } else {
                                                  (responseObject==nil)?failResult(nil):processResult(responseObject);
                                              }
                                          }];
    [uploadTask resume];
}
+ (AFHTTPSessionManager*)sharedSessionByCoustom:(NSString*)urls;
{
    static AFHTTPSessionManager *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        [config setHTTPAdditionalHeaders:@{ @"User-Agent" : @"TuneStore iOS 1.0",@"Content-Type": @"text/plain"}];
        _sharedClient = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:urls] sessionConfiguration:config];
        _sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    });
    
    return _sharedClient;
}
+ (AFHTTPSessionManager*)sharedSessionByCoustom2:(NSString*)urls;
{
    static AFHTTPSessionManager *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        [config setHTTPAdditionalHeaders:@{ @"User-Agent" : @"TuneStore iOS 1.0",@"Content-Type": @"application/json; encoding=utf-8"}];
        _sharedClient = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:urls] sessionConfiguration:config];
        _sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    });
    
    return _sharedClient;
}
@end

@implementation SHTTPSessionClient

+ (SHTTPSessionClient *)sharedSessionClientWithUrl:(NSString*)urls
{
    static SHTTPSessionClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        [config setHTTPAdditionalHeaders:@{ @"User-Agent" : @"TuneStore iOS 1.0",@"Content-Type": @"application/json"}];
        _sharedClient = [[SHTTPSessionClient alloc] initWithBaseURL:[NSURL URLWithString:urls] sessionConfiguration:config];
        _sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    });
    
    return _sharedClient;
}
- (void)POST_Path_File_Session:(NSString *)path
                   _Parameters:(NSMutableDictionary *)parameters
                     _DataUrls:(NSString*)dataUrls
                   _UpDataUrls:(NSString*)upDataUrls
                         block:(void (^)(id, NSURLSessionDataTask *))processResult
                     failblock:(void (^)(NSError *, NSURLSessionDataTask *))failResult
{
    NSString *urls = [NSString stringWithFormat:@"%@%@",upDataUrls,path];
    NSDictionary *parametersDic = parameters;
    NSMutableURLRequest *request1 = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
                                                                                               URLString:urls
                                                                                              parameters:parametersDic
                                                                               constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                                                                                   NSError *e;
                                                                                   [formData appendPartWithFileURL:[NSURL fileURLWithPath:dataUrls] name:@"sents" error:&e];
                                                                                   if (e) {
                                                                                       SNLog(@"Error =====> %@\n",e.localizedDescription);
                                                                                   }
                                                                               } error:nil];
    
    
    NSURLSessionUploadTask *uploadTask = [self uploadTaskWithStreamedRequest:request1
                                                                    progress:nil
                                                           completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                                                               if (error) {
                                                                   SNLog(@"Error =====> %@\n", error);
                                                               } else {
                                                                   SNLog(@" =====> %@\n", responseObject);
                                                               }
                                                           }];
    [uploadTask resume];
}
- (void)POST_Path_Session:(NSString *)path
              _Parameters:(NSMutableDictionary *)parameters
                    block:(void(^)(id rDictionary,NSURLSessionDataTask *rTask))processResult
                failblock:(void(^)(NSError *error,NSURLSessionDataTask *rTask))failResult
{
    NSURLSessionDataTask *task = [self POST:path
                                 parameters:parameters
                                    success:^(NSURLSessionDataTask *task, id responseObject) {
                                        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
                                        
                                        SNLog(@"=====> %ld\n",(long)httpResponse.statusCode);
                                        if (httpResponse.statusCode == 200) {
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                processResult(responseObject,task);
                                            });
                                        } else {
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                processResult(nil,task);
                                            });
                                        }
                                    } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                        failResult(error,task);
                                    }];
    SNLog(@"=====> %@\n",task.originalRequest);
}
- (void)GET_Path_Session:(NSString *)path
             _Parameters:(NSMutableDictionary *)parameters
                   block:(void(^)(id rDictionary,NSURLSessionDataTask *rTask))processResult
               failblock:(void(^)(NSError *error,NSURLSessionDataTask *rTask))failResult
{
    NSURLSessionDataTask *task = [self GET:path
                                parameters:parameters
                                   success:^(NSURLSessionDataTask *task, id responseObject) {
                                       NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
                                       
                                       SNLog(@"=====> %ld\n",(long)httpResponse.statusCode);
                                       if (httpResponse.statusCode == 200) {
                                           dispatch_async(dispatch_get_main_queue(), ^{
                                               processResult(responseObject,task);
                                           });
                                       } else {
                                           dispatch_async(dispatch_get_main_queue(), ^{
                                               processResult(nil,task);
                                           });
                                       }
                                   } failure:^(NSURLSessionDataTask *task, NSError *error) {
                                       failResult(error,task);
                                   }];
    SNLog(@"=====> %@\n",task.originalRequest);
}
@end
#pragma mark SHTTPConnectionClient（AFNetworking）
@implementation SHTTPConnectionClient
#pragma mark *****初始化
+(SHTTPConnectionClient *)sharedConnectionClientWithUrl:(NSString*)urls
{
    static dispatch_once_t pred;
    static SHTTPConnectionClient *_sharedClient = nil;
    dispatch_once(&pred, ^{
        _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:urls]];
    });
    return _sharedClient;
}
#pragma mark *****设置RequestOperation提交格式
-(id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    //申明返回的结果是json类型
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    self.requestSerializer = [AFJSONRequestSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    self.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    //    self.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    return self;
}
- (void)POST_Path_Connection:(NSString *)path
                 _Parameters:(NSMutableDictionary *)parameters
                       block:(void(^)(id rDictionary,AFHTTPRequestOperation *rOperation))processResult
                   failblock:(void(^)(NSError *error,AFHTTPRequestOperation *rOperation))failResult
{
    
    [self POST:path
    parameters:parameters
       success:^(AFHTTPRequestOperation *operation, id responseObject) {
           NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)operation.response;
           SNLog(@"=====> %ld\n",(long)httpResponse.statusCode);
           if (httpResponse.statusCode == 200) {
               dispatch_async(dispatch_get_main_queue(), ^{
                   processResult(responseObject,operation);
               });
           } else {
               dispatch_async(dispatch_get_main_queue(), ^{
                   processResult(nil,operation);
               });
           }
       } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
           failResult(error,operation);
       }];
}

- (void)GET_Path_Connection:(NSString *)path
                _Parameters:(NSMutableDictionary *)parameters
                      block:(void(^)(id rDictionary,AFHTTPRequestOperation *rOperation))processResult
                  failblock:(void(^)(NSError *error,AFHTTPRequestOperation *rOperation))failResult
{
    [self GET:path
   parameters:parameters
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)operation.response;
          SNLog(@"=====> %ld\n",(long)httpResponse.statusCode);
          if (httpResponse.statusCode == 200) {
              dispatch_async(dispatch_get_main_queue(), ^{
                  processResult(responseObject,operation);
              });
          } else {
              dispatch_async(dispatch_get_main_queue(), ^{
                  processResult(nil,operation);
              });
          }
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          failResult(error,operation);
      }];
}




@end